<template>
  <van-swipe-cell v-for="(item, index) in cartDetailList" :key="item">
    <van-card
      :price="item.currentPrice.toFixed(2)"
      :desc="item.title"
      :title="item.productName"
      class="goods-card"
      :thumb="item.imgURL[0]"
    >
      <template #footer>
        <van-checkbox v-model="item.pChecked" @click="oneClick"></van-checkbox>
        <van-stepper
          v-model="item.productNum"
          theme="round"
          button-size="22"
          disable-input
          @click="changeNum"
        />
      </template>
    </van-card>
    <template #right>
      <van-button
        square
        text="删除"
        type="danger"
        class="delete-button"
        @click="cartDel(index)"
      />
    </template>
  </van-swipe-cell>
</template>
<script>
import { reactive } from "vue";
import { mapState, mapActions, mapMutations } from "vuex";
import { getCommodityDetailApi, postUpdateCartListApi } from "@/utils/api";
export default {
  setup() {
    const cList = reactive([]);
    return {
      cList,
    };
  },
  async created() {
    await this.getCartList({ userId: localStorage.getItem("userid") });
    //数据从购物车列表转到详细的购物车列表
    this.cartList.forEach(async (val) => {
      let res = await getCommodityDetailApi({ pid: val.productId });
      this.cList.push({
        ...res.result[0],
        productNum: val.productNum,
        pChecked: false,
      });
    });
    this.updateCartDetailList({ list: this.cList });
  },
  computed: {
    ...mapState("cart", ["cartList", "cartDetailList"]),
  },
  methods: {
    ...mapMutations("cart", ["updateCartDetailList"]),
    ...mapActions("cart", ["getCartList"]),
    oneClick() {
      //更新购物车详情列表
      this.updateCartDetailList({ list: this.cList });
    },
    async changeNum() {
      //更行购物车数据库
      this.updateCartDetailList({ list: this.cList });
      await postUpdateCartListApi({
        uid: localStorage.getItem("userid"),
        carr: this.cartList,
      });
    },
    //购物车删除
    async cartDel(index) {
      console.log(localStorage.getItem("userid"));
      this.cList.splice(index, 1);
      this.updateCartDetailList({ list: this.cList });
      await postUpdateCartListApi({
        uid: localStorage.getItem("userid"),
        carr: this.cartList,
      });
    },
  },
};
</script>

<style lang="less">
.goods-card {
  margin: 5px;
  border-radius: 5px;
  background-color: white;
  .van-card__footer {
    margin-top: 5px;
  }
  .van-checkbox {
    position: absolute;
    // top: 50%;
    // transform: translateY(-50%);
  }
}
.delete-button {
  height: 100%;
}
</style>
